"""
验证 HuaTuoGPT 是否正确安装
"""
import sys
from pathlib import Path

# 添加项目路径
sys.path.insert(0, str(Path(__file__).parent / "src" / "backend"))

print("=" * 80)
print("🔍 验证 HuaTuoGPT 安装")
print("=" * 80)
print("")

# 步骤 1: 检查依赖
print("📋 步骤 1/3: 检查依赖...")
try:
    import torch
    print(f"   ✅ PyTorch {torch.__version__}")
    print(f"   ✅ CUDA 可用: {torch.cuda.is_available()}")
    if torch.cuda.is_available():
        print(f"   ✅ GPU: {torch.cuda.get_device_name(0)}")
        gpu_memory = torch.cuda.get_device_properties(0).total_memory / 1024**3
        print(f"   ✅ GPU 显存: {gpu_memory:.1f}GB")
except ImportError as e:
    print(f"   ❌ PyTorch 未安装: {e}")
    print("")
    print("请运行: pip install torch")
    sys.exit(1)

try:
    import transformers
    print(f"   ✅ Transformers {transformers.__version__}")
except ImportError as e:
    print(f"   ❌ Transformers 未安装: {e}")
    print("")
    print("请运行: pip install transformers")
    sys.exit(1)

# 步骤 2: 加载配置
print("")
print("📋 步骤 2/3: 加载配置...")
try:
    from app.core.config import settings
    print(f"   ✅ 配置加载成功")
    print(f"   ✅ USE_HUATUOGPT: {settings.USE_HUATUOGPT}")
    print(f"   ✅ 模型: {settings.HUATUOGPT_MODEL_NAME}")
    
    if not settings.USE_HUATUOGPT:
        print("")
        print("   ⚠️  警告: USE_HUATUOGPT 设置为 False")
        print("   请在 config.py 中设置 USE_HUATUOGPT = True")
        sys.exit(1)
        
except Exception as e:
    print(f"   ❌ 配置加载失败: {e}")
    import traceback
    traceback.print_exc()
    sys.exit(1)

# 步骤 3: 加载 HuaTuoGPT
print("")
print("📋 步骤 3/3: 加载 HuaTuoGPT 模型...")
print("   ⏳ 正在加载（首次可能需要 1-2 分钟）...")

try:
    from app.core.huatuogpt_wrapper import get_huatuogpt
    
    wrapper = get_huatuogpt()
    model_info = wrapper.get_model_info()
    
    print("")
    print("   ✅ HuaTuoGPT 加载成功！")
    print("")
    print("   📊 模型信息:")
    for key, value in model_info.items():
        print(f"      - {key}: {value}")
    
    print("")
    print("=" * 80)
    print("🎉 验证成功！HuaTuoGPT 已正确安装并可用！")
    print("=" * 80)
    print("")
    print("下一步：")
    print("1. 启动 Ollama: ollama serve")
    print("2. 启动后端: cd src\\backend && python -m app.main")
    print("3. 运行测试: python test_dual_model_evaluator.py")
    print("")
    
except Exception as e:
    print("")
    print(f"   ❌ 加载失败: {e}")
    print("")
    print("=" * 80)
    print("❌ 验证失败")
    print("=" * 80)
    print("")
    print("可能的原因：")
    print("1. 模型文件未完整下载")
    print("   解决：运行 python download_huatuogpt.py 重新下载")
    print("")
    print("2. GPU 显存不足（需要约 6-7GB）")
    print("   解决：关闭其他占用 GPU 的程序")
    print("")
    print("3. 配置路径错误")
    print("   解决：检查 config.py 中的 HUATUOGPT_MODEL_NAME")
    print("")
    print("详细错误信息：")
    import traceback
    traceback.print_exc()
    sys.exit(1)

